<?php

namespace app\api\controller;

use app\admin\model\User as UserModel;
use app\common\controller\Api;
use app\admin\model\Template as TemplateModel;
use app\common\model\Category as CategoryModel;
use app\admin\model\Record as RecordModel;
use think\facade\Db;
use third\Esign;

/**
 * 首页接口.
 */
class Contract extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];


    public function cate()
    {
        $list = (new CategoryModel())->getCategoryArray('template', 'normal');

        $template_ids = (new RecordModel())->where('user_id', $this->auth->id)->where('status', 2)->column('template_id');
        $cate = [];
        if ($template_ids) {
            $cate[] = [
                'id' => 9999,
                'name' => '我的常用',
            ];
        }
        foreach ($list as $k => $v) {
            $cate[] = [
                'id' => $v['id'],
                'name' => $v['name'],
            ];
        }
        $this->success('请求成功', ['list' => $cate]);
    }

    /**
     * 合同模板列表
     * @return void
     */
    public function list()
    {
        $keywords = $this->request->get('keywords');
        $category_id = $category_id2 = $this->request->get('category_id');
        $template_ids = [];
        //表示我的常用
        if ($category_id == 9999) {
            $template_ids = (new RecordModel())->where('user_id', $this->auth->id)->where('status', 2)->column('template_id');
            $category_id = 0;
        }
        $size = $this->request->get('size', 10);
        //根据用户标签获取模板
        $userinfo = $this->auth->getUserinfo();
        $label_ids = $userinfo['label_ids'];
        $label_ids = explode(',', $label_ids);

        //查询标签是否被禁用
        $label_ids = Db::name('label')->where('id', 'in', (array)$label_ids)->where('status', 1)->column('id');
        $user_temp_ids = [];
        foreach ($label_ids as $vv) {
            $temp_ids = Db::name('template')->where('user_tags', 'like', "%{$vv}%")->column('id');
            $user_temp_ids = array_merge($user_temp_ids, $temp_ids);
        }
        //查询为空的 未设置用户分组的 也可以查看
        $unusertags = Db::name('template')->where('user_tags', '')->column('id');
        $user_temp_ids = array_merge($user_temp_ids, $unusertags);
        if ($category_id2 == 9999) {
            $template_ids = $template_ids ? array_intersect($template_ids, $user_temp_ids) : [-1];
        } else {
            $template_ids = $user_temp_ids;
        }
        $list = (new TemplateModel())->getList(['status' => 1, 'category_id' => $category_id, 'template_ids' => $template_ids, 'keywords' => $keywords], $size, 'id,title,desc,createtime,file_url', 'weigh desc');

        $allow_submit = 1;
        if ($this->auth->xieyi <= 0||$this->auth->viptime<time()) {
            $allow_submit = 0;
        }
        $list['allow_submit'] =$allow_submit;
        $this->success('请求成功', $list);
    }


    /**
     * 合同模板详情
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNot
     * FoundException
     * @throws \think\exception\DbException
     */
    public function detail()
    {

        $template_id = $this->request->get('template_id');
        $info = (new TemplateModel())->where(['id' => $template_id])->find();
        if (empty($info)) {
            $this->error('参数异常');
        }
        $image_list = [];
        if ($info['image_path']) {
            $image_list = explode(',', $info['image_path']);
        } else {
            if ($info['file_url']) {
                $filekey = 'template_' . $info['id'] . "_" . time();
                $file_url_arr = explode('uploads', $info['file_url']);
                $filename = public_path() . 'uploads' . $file_url_arr[1];
                $pdf = new \Spatie\PdfToImage\Pdf($filename);
                $total = $pdf->getNumberOfPages();

                for ($i = 1; $i <= $total; $i++) {
                    $pdf->setOutputFormat('png')
                        ->setCompressionQuality(100)
                        ->setPage($i)
                        ->setPage($i)
                        ->saveImage(public_path() . 'uploads/pdf2image/' . $filekey . "_" . $i . '.png');
                    $image_list[] = '/uploads/pdf2image/' . $filekey . "_" . $i . '.png';
                }
                (new TemplateModel())->where('id', $info['id'])->update(['image_path' => implode(',', $image_list)]);
            }
        }
        foreach ($image_list as &$url) {
            $url = $this->request->domain() . $url;
        }
        $info['image_path'] = $image_list;



        $allow_submit = 1;
        if ($this->auth->xieyi <= 0||$this->auth->viptime<time()) {
            $allow_submit = 0;
        }
        $info['allow_submit'] = $allow_submit;
        $info['is_auth'] = $this->auth->is_auth;
        $this->success('成功', $info);


    }

    /**
     * 我的合同列表
     * @return void
     */
    public function mylist()
    {

        $data = $this->request->get([
            'keywords' => '',
            'page' => 1,
            'createtime' => '',
            'signtime' => '',
            'status' => -1,
            'sign_type' => 0,
            'size' => 12,

        ]);

//        dump($data);die;

        $data['user_id'] = $this->auth->id;
        $this->loadlang('record');
        $list = (new RecordModel())->getList($data, $data['size']);
        $datacount = [
            'sign_self' => (new RecordModel())->where('user_id', $this->auth->id)->where('status', 'in', [0, 1])->where('user1_sign_status', 'in', [0, 1])->count(),
            'sign_other' => (new RecordModel())->where('user_id', $this->auth->id)->where('status', 'in', [0, 1])->where('user2_sign_status', 'in', [0, 1])->count(),
        ];


        $allow_submit = 1;
        if ($this->auth->xieyi <= 0||$this->auth->viptime<time()) {
            $allow_submit = 0;
        }
        $this->success('请求成功', ['list' => $list, 'datacount' => $datacount,'allow_submit'=>$allow_submit]);
    }


    /**
     * 获取模板控件
     * @return void
     */
    public function components()
    {
        $Esign = new Esign();
        $template_id = $this->request->get('template_id');
        $info = (new TemplateModel())->where(['id' => $template_id])->find();
        if (empty($info) || $info['status'] != 1) {
            $this->error('参数异常');
        }
        if ($this->auth->xieyi <= 0||$this->auth->viptime<time()) {
            $this->error('您的会员已到期或可用协议份数不足，请联系客服充值 ',['xinyi'=>0]);
        }
        if (!$info['docTemplateId']) {
            $this->error('合同模板异常');
        }
        $components = $Esign->templatesComponents($info['docTemplateId']);

        $edit_content = [];
        $singer = [];
//        dump($components);die;
        foreach ($components['data']['components'] as $vv) {

            if ($vv['componentType'] == 6) {
                $singer[] = $vv;
            } else {
                $edit_content[] = $vv;
            }
        }

        $_singer = [];
        $mesign_key = -1;
        foreach ($singer as $k => $item) {
            if ($item['componentKey'] == 'mesign') {
                $_singer[] = $item;
                $mesign_key = $k;
            }
        }
        unset($singer[$mesign_key]);
        $_singer = array_merge($_singer, $singer);
        cache('temp_components_' . $template_id, $_singer);
        $this->success('请求成功', ['edit_content' => $edit_content, 'singer' => $_singer]);
    }


    /**
     * 发起合同
     * @return void
     */
    public function submit()
    {
        try {
            $Esign = new Esign();

            $template_id = $this->request->post('template_id');
            $data = $this->request->post('data', '', null);
            $components = $this->request->post('components', '', null);

            $data = json_decode($data, true);
            $components = json_decode($components, true);

            $info = (new TemplateModel())->where(['id' => $template_id])->find();
            if (empty($info) || $info['status'] != 1 || empty($data) || empty($components)) {
                $this->error('参数异常');
            }
            if ($this->auth->xieyi <= 0||$this->auth->viptime<time()) {
                $this->error('您的会员已到期或可用协议份数不足，请联系客服充值 ',['xinyi'=>0]);
            }
            $record_sn = date('YmdHis') . rand(10000, 99999);
            $_components = [];
            foreach ($components as $vv) {
                $_components[] = [
                    'componentId' => $vv['componentId'],
                    'componentValue' => is_array($vv['componentValue']) ? json_encode($vv['componentValue'], JSON_UNESCAPED_UNICODE) : $vv['componentValue'],
                ];
            }

            $result = $Esign->createByDocTemplate($info['docTemplateId'], $info['title'], $_components);
            if (!$result) {
                $this->error($Esign->getError());
            }

//        dump($result);die;
            $fileid = $result['fileId'];

            $record = [
                'title' => $info['title'],
                'category_ids' => $info['category_ids'],
                'record_sn' => $record_sn,
//                'username1' => $this->auth->username,
//                'mobile1' => $this->auth->mobile,
                'createtime' => time(),
                'signtime' => time(),
                'user_id' => $this->auth->id,
                'username1' => isset($data[0]['username']) ? $data[0]['username'] : '',
                'mobile1' => isset($data[0]['mobile']) ? $data[0]['mobile'] : '',
                'username2' => isset($data[1]['username']) ? $data[1]['username'] : '',
                'mobile2' => isset($data[1]['mobile']) ? $data[1]['mobile'] : '',
                'user2_sign_status' => 0,
                'esign_fileid' => $fileid,
                'template_id' => $info['id'],
                'edit_url' => '',
                'components' => json_encode($components),
                'json' => json_encode($data),
            ];

            $signer = [];

            $temp_components = cache('temp_components_' . $template_id);

            if (isset($record['username1']) && $record['username1'] && isset($record['mobile1']) && $record['mobile1']) {
                $s1 = ['username' => $record['username1'], 'mobile' => $record['mobile1'], 'noticeTypes' => '', 'freeMode' => true];

                if (isset($temp_components[0])) {
                    $s1['positionPage'] = $temp_components[0]['componentPosition']['componentPageNum'];
                    $s1['positionX'] = $temp_components[0]['componentPosition']['componentPositionX'];
                    $s1['positionY'] = $temp_components[0]['componentPosition']['componentPositionY'];
                    $s1['freeMode'] = false;
                }
                $signer[] = $s1;

            }
            if (isset($record['username2']) && $record['username2'] && isset($record['mobile2']) && $record['mobile2']) {
                $s2 = ['username' => $record['username2'], 'mobile' => $record['mobile2'], 'noticeTypes' => 1,'freeMode'=>true];
                if (isset($temp_components[1])) {
                    $s2['positionPage'] = $temp_components[1]['componentPosition']['componentPageNum'];
                    $s2['positionX'] = $temp_components[1]['componentPosition']['componentPositionX'];
                    $s2['positionY'] = $temp_components[1]['componentPosition']['componentPositionY'];
                    $s2['freeMode'] = false;
                }
                $signer[] = $s2;
            }
            $notifyurl = $this->request->domain() . '/api/esign/notify';
            $flowId = $Esign->createByFile($fileid, $info['title'], $info['title'], $signer, $notifyurl, $this->auth->psnId);

            if (!$flowId) {
                $this->error($Esign->getError());
            }
            $result = $Esign->getSignUrl($flowId, $this->auth->mobile);
            if (!$result) {
                $this->error($Esign->getError());
            }

            $record['sign_url'] = $result->url;
            $record['flowId'] = $flowId;
            $record['status'] = 1;
            $record['user1_sign_status'] = 1;
            $insertresult = (new RecordModel())->insert($record);
            if (!$insertresult) {
                $this->error('失败');
            }
            (new UserModel())->where('id', $this->auth->id)->dec('xieyi', 1)->update();

            $this->success('成功', $result);
        } catch (\Exception $e) {
            $this->error('系统异常:' . $e->getMessage());
        }
    }

    public function sign()
    {

        try {
            $fileid = $this->request->get('fileid');
            $customBizNum = $this->request->get('customBizNum');
            $RecordModel = new RecordModel();
            $Esign = new Esign();
            if (!$fileid || !$customBizNum) {
                $this->error('参数错误');
            }

            $record = $RecordModel->where('record_sn', $customBizNum)->where('user_id', $this->auth->id)->find();
            if (empty($record)) {
                $this->error('记录信息异常');
            }
            if ($record['status'] != 0) {
                $this->error('记录状态异常');
            }
            $info = (new TemplateModel())->where(['id' => $record['template_id']])->find();
            if (empty($info) || $info['status'] != 1) {
                $this->error('模板异常');
            }

            $signer = [];
            if (isset($record['username1']) && $record['username1'] && isset($record['mobile1']) && $record['mobile1']) {
                $signer[] = ['username' => $record['username1'], 'mobile' => $record['mobile1']];
            }
            if (isset($record['username2']) && $record['username2'] && isset($record['mobile2']) && $record['mobile2']) {
                $signer[] = ['username' => $record['username2'], 'mobile' => $record['mobile2']];
            }

            $notifyurl = $this->request->domain() . '/api/esign/notify';
            $flowId = $Esign->createByFile($fileid, $info['title'], $info['title'], $signer, $notifyurl);

            if (!$flowId) {
                $this->error($Esign->getError());
            }
            $result = $Esign->getSignUrl($flowId, $this->auth->mobile);
            if (!$result) {
                $this->error($Esign->getError());
            }
            $updatestatus = $RecordModel->where('id', $record['id'])->update([
                'sign_url' => $result->shortUrl,
                'flowId' => $flowId,
                'esign_fileid' => $fileid,
                'status' => 1,
                'user1_sign_status' => 1,
            ]);
            if ($updatestatus === false) {
                $this->error('失败');
            }
            (new UserModel())->where('id', $this->auth->id)->dec('xieyi', 1)->update();
            $this->success('成功', $result);
        } catch (\Exception $e) {
            $this->error('系统异常:' . $e->getMessage());
        }

    }

    /**
     * 下载签署文件
     * @return void
     */
    public function downloadfile()
    {
        $RecordModel = new RecordModel();
        $record_id = $this->request->get('record_id');
        $record = $RecordModel->where('id', $record_id)->where('user_id', $this->auth->id)->find();
        if (empty($record)) {
            $this->error('记录异常');
        }
        $Esign = new Esign();
        $result = $Esign->fileDownloadUrl($record['flowId']);

        $this->success('成功', $result);
    }

    /**
     * 填写合同
     * @return void
     */
    public function edit()
    {
        $record_id = $this->request->get('record_id');
        $recordModel = new RecordModel();
        $info = $recordModel->where('id', $record_id)->where('user_id', $this->auth->id)->find();
        if (empty($info)) {
            $this->error('参数异常');
        }
        $Esign = new Esign();
        $result = $Esign->getSignUrl($info['flowId'], $this->auth->mobile);
        if (!$result) {
            $this->error($Esign->getError());
        }
        $this->success('成功', $result);
    }

    /**
     * 合同模板详情
     * @return void
     */
    public function contract_detail()
    {
        $template_id = $this->request->get('template_id');
        $info = (new TemplateModel())->where(['id' => $template_id])->find();
        $this->success('成功', $info);
    }

    /**
     * 撤销
     * @return void
     */
    public function revoke()
    {
        $record_id = $this->request->get('record_id');
        $recordModel = new RecordModel();
        $info = $recordModel->where('id', $record_id)->where('user_id', $this->auth->id)->find();
        if (empty($info)) {
            $this->error('参数异常');
        }
        $Esign = new Esign();
        $result = $Esign->revokeFlow($info['flowId']);
        if (!$result) {
            $this->error($Esign->getError());
        }
        if ($result['code'] == 0) {
            $recordModel->where('id', $record_id)->update(['updatetime' => time(), 'status' => 3]);
        } else {
            $this->error($result['message']);
        }
        $this->success('成功');
    }


    /**
     * 删除
     * @return void
     */
    public function delete()
    {
        $record_id = $this->request->get('record_id');
        $recordModel = new RecordModel();
        $info = $recordModel->where('id', $record_id)->where('user_id', $this->auth->id)->find();
        if (empty($info)) {
            $this->error('参数异常');
        }

        if ($info['status'] != 3 && $info['status'] != 5) {
            $this->error('合同不允许删除');
        }
        $result = $recordModel->where('id', $record_id)->delete();
        if ($result) {
            $this->success('成功');
        } else {
            $this->error($result['message']);
        }
    }


    /**
     * 下载接口
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function content_file()
    {
        $RecordModel = new RecordModel();
        $record_id = $this->request->get('record_id');
        $record = $RecordModel->where('id', $record_id)->where('user_id', $this->auth->id)->find();
        if (empty($record)) {
            $this->error('记录异常');
        }
        if ($record['image_path']) {
            $image_list = explode(',', $record['image_path']);
            $filepath = $record['pdf_path'];
        } else {
            $Esign = new Esign();
            $result = $Esign->fileDownloadUrl($record['flowId']);
            $downloadUrl = $result['data']['files'][0]['downloadUrl'];
            $filepath = 'uploads/pdf/' . $record_id . '.pdf';
            $filename = public_path() . $filepath;
            $this->pdfdownload($downloadUrl, $filename);

            $pdf = new \Spatie\PdfToImage\Pdf($filename);
            $total = $pdf->getNumberOfPages();
            $image_list = [];
            for ($i = 1; $i <= $total; $i++) {
                $pdf->setOutputFormat('png')
                    ->setCompressionQuality(100)
                    ->setPage($i)
                    ->setPage($i)
                    ->saveImage(public_path() . 'uploads/pdf2image/' . $record_id . "_" . $i . '.png');

                $image_list[] = '/uploads/pdf2image/' . $record_id . "_" . $i . '.png';
            }

            $RecordModel->where('id', $record_id)->update(['image_path' => implode(',', $image_list), 'pdf_path' => '/' . $filepath]);

        }
        $_image_list = [];
        foreach ($image_list as $item) {
            $_image_list[] = $this->request->domain() . '/' . $item;
        }
        $this->success('成功', ['image' => $_image_list, 'pdf_path' => $this->request->domain() . '/' . $filepath]);
    }


    /**
     * pdf下载
     * @param $url
     * @param $filename
     * @return false|mixed|string
     */
    function pdfdownload($url, $filename = "")
    {
        if ($url == "") return false;
        ob_start();
        readfile($url);
        $img = ob_get_contents();
        ob_end_clean();
        $size = strlen($img);
        $fp2 = @fopen($filename, "a");
        fwrite($fp2, $img);
        fclose($fp2);
        return $filename;
    }


    public function cert_data()
    {

        $RecordModel = new RecordModel();
        $record_id = $this->request->get('record_id');
        $record = $RecordModel->where('id', $record_id)->where('user_id', $this->auth->id)->find();
        if (empty($record)) {
            $this->error('记录异常');
        }

        if (!$record['antTransactionId']) {
            $Esign = new Esign();
            $result = $Esign->antchain_file_info($record['flowId']);
            if (!$result) {
                $this->error($Esign->getError());
            }

//            dump($result);die;
            $RecordModel->where('id', $record_id)->update([
                'antTransactionId' => $result['antchainFiles'][0]['antTransactionId'],
                'antTxHash' => $result['antchainFiles'][0]['antTxHash'],
                'fileHash' => $result['antchainFiles'][0]['fileHash'],
            ]);
            $record = $RecordModel->where('id', $record_id)->where('user_id', $this->auth->id)->find();
        }

        $data = [
            'record_sn' => $record['record_sn'],
            'title' => $record['title'],
            'fileHash' => $record['fileHash'],
            'antTxHash' => $record['antTxHash'],
            'recordstatus' => '已完成签署',
            'user1_sign_time' => date('Y-m-d H:i:s', $record['user1_sign_time']),
            'user2_sign_time' => date('Y-m-d H:i:s', $record['user2_sign_time']),
            'username1' => $record['username1'],
            'username2' => $record['username2'],

        ];

        $this->success('成功', $data);

    }


    public function pdf2image()
    {
        $pathToPdf = root_path() . '租房合同协议书样例.pdf';
        $pdf = new \Spatie\PdfToImage\Pdf($pathToPdf);

        $total = $pdf->getNumberOfPages();
        $sn = rand(10000, 99999);
        for ($i = 1; $i <= $total; $i++) {
            $pdf->setOutputFormat('png')
                ->setCompressionQuality(100)
                ->setPage($i)
                ->setPage($i)
                ->saveImage(public_path() . 'uploads/pdf2image/' . $sn . "_" . $i . '.png');
        }

    }

}
